$.datepicker.setDefaults({
  showOn: "both"
  , buttonImageOnly: true
  , buttonImage: '/images/btn_cale.gif'
  , buttonText: "달력"
  , dateFormat : "yy.mm.dd"
  , dayNames : ["일","월","화","수","목","금","토"]
  , dayNamesMin: ["일","월","화","수","목","금","토"]
  , monthNames: [ "1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월" ]
});

//페이지 초기화 함수
function fnCmmInitalizeContent() {
	$(".datepicker").datepicker();
	$('button:not(.btn,.fc-button), a.btn').each(function() {
		var optionMap = {
			'등록' 			 : {icons : {primary:'ui-icon-plus'} }
			,'조회' 		 : {icons : {primary:'ui-icon-search'} }		
			,'수정' 		 : {icons : {primary:'ui-icon-pencil'} }			
			,'삭제' 		 : {icons : {primary:'ui-icon-trash'} }				
			,'저장' 		 : {icons : {primary:'ui-icon-disk'} }			
			,'전송' 		 : {icons : {primary:'ui-icon-transferthick-e-w'} }						
			,'닫기' 		 : {icons : {primary:'ui-icon-closethick'} }			
			,'초기화'		 : {icons : {primary:'ui-icon-arrowreturn-1-w'} } 
			,'엑셀 다운로드' : {icons : {primary:'ui-icon-disk'} }
			,'자세히 보기'		 : {icons : {primary:'ui-icon-calculator'} } 
		}
		var option =  optionMap[$(this).text().trim()] || {};
		option.text = !$(this).hasClass("ui-button-icon-only") ;
console.debug(option);
		$(this).button(option);
	});
//	$(".searchTb select").selectmenu();
	$( ".accordion" ).accordion({collapsible: true, heightStyle: "content"});
//	$( ".accordion" ).section();
	$( "input[type=radio]").buttonset();
	$(".tab").tabs({load:fnCmmInitalizeContent});
	
	$('img.ui-datepicker-trigger').css({'cursor':'pointer', 'margin-left':'5px'});  //아이콘(icon) 위치
    $('img.ui-datepicker-trigger').attr('align', 'absmiddle');
	
	$("h3.bult").each(function() {
		$(this).find("span.ui-icon").remove();
		$(this).addClass("").css("color","#e17009").prepend("<span class='ui-icon ui-icon-triangle-1-e' style='display:inline-block'></span>");
	});
	
	fnCmmGridResize();
}

//grid resize
function fnCmmGridResize(target) {
	if ( !target ) target = "body";
	var grid = $(target).find(".ui-jqgrid-btable");
	grid.each(function() {
		var parent = $(this).parents(".ui-jqgrid").parent();
		$(this).setGridWidth(parent.width());
	});
	
}
//페이지 초기화
$(document).ready(function(e) {
	fnCmmInitalizeContent();

});

//page resize
$(window).resize(function() {
	fnCmmGridResize("body");
});


$( document ).ajaxStart(function() {

	$("body").loadingStart();
});

$( document ).ajaxComplete(function(event, XMLHttpRequest, ajaxOptions) {
    $("body").loadingStop();
});

$.ajaxSetup({cache:false});

//ajax 에러처리
$( document ).ajaxError(function() {
  if ( console ) console.log(arguments);
});
//페이지(팝업,새창,레이어 관련 클릭 이벤트 
$(document).on("click", "a.new" , function() { //새창열기 이벤트

	var url = this.href;
	$(this).newWin(url, $(this).text());

	return false;
})
.on("click", ".close_btn, .close", function() { //닫기버튼 이벤트
	var parent = $(this).parents(".new_main, .layer_main, .ui-dialog ");
	if ( parent.is(".ui-dialog") ) {
//		$(parent).dialog( "destroy");
		$(this).parents(".ui-dialog").remove();
	} else {
		
		$(this).parents("article.content, .layer_main ").remove();
	}
	
})
.on("click", ".layer", function() {//레이어
	var url = this.href;
	var parent = $(document.body);
	var pageNavi = parent.find("h2").text() + " > " + $(this).text();
	/*
	var content = $('<div class="ui-dialog ui-widget ui-widget-content ui-corner-all ui-front"><div class="ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix"><span class="ui-dialog-title"></span><button type="button" class="ui-dialog-titlebar-close close_btn" title="닫기"></button></div></div>').appendTo(parent);
	content.find("button").button({icons : {primary:'ui-icon-close'}, text:false});
	//fnCmmDialog(url, {title:pageNavi, width:800});
	$.ajax({
	   type: "POST",
	   url: url,
	   success: function(data){
			
			content.append($(data).addClass("ui-dialog-content")).draggable({handle:'div.ui-dialog-titlebar'}).resizable();
			content.find("span.ui-dialog-title").text(pageNavi);
			content.css({width:800, zIndex:101});
			$('<div class="ui-widget-overlay ui-front"></div>').insertAfter(content);
			
			fnCmmInitalizeContent();
			
	   }
	   
   
 	});*/
	fnCmmDialog(url, {title:pageNavi, width:800});
	return false;
})
.on("click", ".dialog", function(e) { //팝업창
	e.preventDefault();
	var url = this.href;
	var title  = this.title || $(this).text() || '팝업';

	fnCmmDialog(url, {title:title, width:800, modal:false});

})
;

//섹션 공통 처리
jQuery.fn.section = function() {
	$(this).addClass("ui-widget ui-accordion");
	$(this).find("h3").addClass("ui-widget-header ui-accordion-header ui-corner-top");
	$(this).find(">div").addClass("ui-widget-content ui-accordion-content ui-corner-bottom");
}

//새창열기
jQuery.fn.newWin = function(url, title) {

	var parent = $(this).parents("article.content");
	var pageNavi = parent.find("h2").text() + (title? " > " + title : "");

    var content = $("<article class='content'><h2></h2><button class='close_btn ui-button-icon-only'>닫기</button><div class='content'></div></article>").insertAfter(parent);
	//content.css({"margin-left": "-800px", width : '0px'}).animate({width:'800px'}).animate({"margin-left": "0px"});
	content.slideDown('slow');
	$.ajax({
	   type: "POST",
	   url: url,
	   success: function(data){

			content.find("div.content").append(data);
			content.find("h2").text(pageNavi);
			
			fnCmmInitalizeContent();
			
	   }
	   
   
 	});
}

//다이얼로그 창 띄우기
function fnCmmDialog(url, opt) {
	return $("body").fnCmmDialog(url, opt);
}
//다이얼로그 창 띄우기
jQuery.fn.fnCmmDialog = function(url, opt){
	if ( !url )  {
		alert("url 파라메터가 넘어오지 않았습니다.");
		return;
	}
	
	var oThis = this;
			
	var opts = {
		autoOpen: true
		, modal: true
		, close : function() {
		  $(this).dialog( "destroy");
		  $(this).remove();
		}
		, resize : function() {
			var parent = $(this).find(".ui-jqgrid-btable").parents(".ui-jqgrid").parent();
			$(this).find(".ui-jqgrid-btable").setGridWidth(parent.width());
		}
	}
	
	$.extend(opts, opt);
	
	//var content = $("<div></div>").dialog(opts);


	$.ajax({
	   type: "POST",
	   url: url,
	   success: function(data){

		   if ( !opts.width ) {
			 //  opts.width = $(data).width() + 20;
		   }
			var content = $("<div></div>");
			content.css({width: opts.width}).append(data);
			$(oThis).append(content);
			//content.remove().dialog(opts).dialog( "moveToTop" );
			content.dialog(opts).dialog( "moveToTop" );
//			
			console.debug(opts);
			//$(data).dialog(opts);
			fnCmmInitalizeContent();
	   }
 	});
	return false;
}
jQuery.fn.exportGrid = function(){

 	var mya = $(this).getDataIDs(); // Get All IDs
	var data = $(this).getRowData(mya[0]); // Get First row to get the
	// labels
	var colNames = new Array();
	var ii = 0;
	for ( var i in data) {
		colNames[ii++] = i;
	} // capture col names
	
	var html = "<html><head>"
			 + '	<meta http-equiv=Content-Type content="application/vnd.ms-excel">'
			+ '<meta name=ProgId content=Excel.Sheet>'
			+ '<meta name=Generator content="Microsoft Excel">'
			+ '<meta http-equiv=Content-Disposition content="attachment; filename=reporteOportunidadesXLS.xls">'
			+ "<style script=&quot;css/text&quot;>"
			+ "table.tableList_1 th {border:1px solid black; text-align:center; "
			+ "vertical-align: middle; padding:5px;}"
			+ "table.tableList_1 td {border:1px solid black; text-align: left; vertical-align: top; padding:5px;}"
			+ "</style>"
			+ "</head>"
			+ "<body><table class='tableList_1'><tr>";
	
	
	for ( var k = 0; k < colNames.length; k++) {
		html = html + "<th>" + colNames[k] + "</th>";
	}
	html = html + "</tr>"; // Output header with end of line
	for (i = 0; i < mya.length; i++) {
		html = html + "<tr>";
		data = $(this).getRowData(mya[i]); // get each row
		for ( var j = 0; j < colNames.length; j++) {
		 html = html + "<td>" + data[colNames[j]] + "</td>"; // output each Row as
					// tab delimited
		}
		html = html + "</tr>"; // output each row with end of line
	}
	html = html + "</table></body></html>"; // end of line at the end
	console.debug(html);
	html = html.replace(/'/g, '&apos;');
	OpenWindow = window.open('', '');
	OpenWindow.document.write(html);
	OpenWindow.document.close();
}

//ajax 로딩중 시작
$.fn.loadingStart = function() {
	
	$(this).each(function() {
		var loader = $('<div class="loading_layer"><div class="loader_bg"></div><div class="loader"></div></div>');
		var size = 32;
		var frame = 12;
	console.debug(this);
		loader.css({ position:"absolute", width:"100%", height:"100%", top:0});
		loader.find(".loader").css(
			{background : "url(/images/sprites2.png)  no-repeat " + size + "px"
			, position : "absolute"
			, left : "50%"
			, top : "50%"
			, margin : "-" + (size/2) + "px 0 0 -" + (size/2) +"px" 
			, width : size
			, height : size});

		$(this).append(loader);
		var i = 0;
		var interval = setInterval( function() {
			if ( i == frame ) i = 0;
			var w =  i * size;
			i++;
			loader.find(".loader").css({backgroundPosition : "-" + w + "px 0"});
		}, 50 );
	
		$(this).data({interval : interval});
	});
	
	return this;
}
//ajax 로딩중 정지
$.fn.loadingStop = function() {
	$(this).each(function() {
		var target = $(this).find("div.loading_layer");
		var interval = $(this).data("interval");
		clearInterval(interval);
		target.remove();
	});
	return this;
	
}


//지도생성
function fnCmmMapControl(elementId, mapLatLng,  defaultLevel ) {
	if ( !mapLatLng) mapLatLng = [35.4210198, 129.0843919];
	var oSeoulCityPoint = new nhn.api.map.LatLng(mapLatLng[0],mapLatLng[1] );

	var defaultLevel = defaultLevel || 8;
	var oMap = new nhn.api.map.Map(document.getElementById(elementId), { 
									point : oSeoulCityPoint,
									zoom : defaultLevel,
									enableWheelZoom : true,
									enableDragPan : true,
									enableDblClickZoom : false,
									mapMode : 1,
									activateTrafficMap : false,
									activateBicycleMap : false,
									minMaxLevel : [ 1, 14 ]       });
										
	var oSlider = new nhn.api.map.ZoomControl();
	oMap.addControl(oSlider);
	oSlider.setPosition({
			top : 10,
			right : 10
	});
	
	var oMapTypeBtn = new nhn.api.map.MapTypeBtn();
	oMap.addControl(oMapTypeBtn);
	oMapTypeBtn.setPosition({
			bottom : 10,
			right : 80
	});
	
	var oThemeMapBtn = new nhn.api.map.ThemeMapBtn();
	oThemeMapBtn.setPosition({
			bottom : 10,
			right : 10
	});
	oMap.addControl(oThemeMapBtn);
	
	
	
	var oSize = new nhn.api.map.Size(7, 7);
	var oOffset = new nhn.api.map.Size(7, 7);
	var oIcon = new nhn.api.map.Icon('/images/dot.png', oSize, oOffset);
	var oCircle = new nhn.api.map.Circle();
	var oInfoWnd = new nhn.api.map.InfoWindow();
	oInfoWnd.setVisible(false);
	oMap.addOverlay(oInfoWnd);
	
	oInfoWnd.setPosition({
			top : 20,
			left :20
	});
	
	var oLabel = new nhn.api.map.MarkerLabel(); // - 마커 라벨 선언.
	oMap.addOverlay(oLabel); // - 마커 라벨 지도에 추가. 기본은 라벨이 보이지 않는 상태로 추가됨.
	
	oInfoWnd.attach('changeVisible', function(oCustomEvent) {
			if (oCustomEvent.visible) {
					oLabel.setVisible(false);
			}
	});
	
	var oPolyline = new nhn.api.map.Polyline([], {
			strokeColor : '#f00', // - 선의 색깔
			strokeWidth : 5, // - 선의 두께
			strokeOpacity : 0.5 // - 선의 투명도
	}); // - polyline 선언, 첫번째 인자는 선이 그려질 점의 위치. 현재는 없음.
	var oPolygon = new nhn.api.map.Polygon([], {
			strokeColor : '#f00', // - 선의 색깔
			strokeWidth : 5, // - 선의 두께
			strokeOpacity : 0.5 // - 선의 투명도
	});
	oMap.addOverlay(oPolygon);
	
	oMap.addOverlay(oPolyline); // - 지도에 선을 추가함.
	
	oMap.attach('mouseenter', function(oCustomEvent) {
	
			var oTarget = oCustomEvent.target;
			// 마커위에 마우스 올라간거면
			if (oTarget instanceof nhn.api.map.Marker) {
					var oMarker = oTarget;
					oLabel.setVisible(true, oMarker); // - 특정 마커를 지정하여 해당 마커의 title을 보여준다.
			}
	});
	
	oMap.attach('mouseleave', function(oCustomEvent) {
	
			var oTarget = oCustomEvent.target;
			// 마커위에서 마우스 나간거면
			if (oTarget instanceof nhn.api.map.Marker) {
					oLabel.setVisible(false);
			}
	});
	
	oMap.attach('click', function(oCustomEvent) {
			var oPoint = oCustomEvent.point;
			var oTarget = oCustomEvent.target;
			console.debug(oPoint.y + " , " + oPoint.x);
			oInfoWnd.setVisible(false);
			// 마커 클릭하면
			if (oTarget instanceof nhn.api.map.Marker) {
					// 겹침 마커 클릭한거면
					if (oCustomEvent.clickCoveredMarker) {
							return;
					}
					// - InfoWindow 에 들어갈 내용은 setContent 로 자유롭게 넣을 수 있습니다. 외부 css를 이용할 수 있으며, 
					// - 외부 css에 선언된 class를 이용하면 해당 class의 스타일을 바로 적용할 수 있습니다.
					// - 단, DIV 의 position style 은 absolute 가 되면 안되며, 
					// - absolute 의 경우 autoPosition 이 동작하지 않습니다. 
					oInfoWnd.setContent('<DIV style="border-top:1px solid; border-bottom:2px groove black; border-left:1px solid; border-right:2px groove black;margin-bottom:1px;color:black;background-color:white; width:auto; height:auto;">'+
							'<span style="color: #000000 !important;display: inline-block;font-size: 12px !important;font-weight: bold !important;letter-spacing: -1px !important;white-space: nowrap !important; padding: 2px 5px 2px 2px !important">' + 
							'발생일시 : 2014.07.18 <br />'
							+ '병해충명: 소나무 재선충<br/>' 
							+ '위치정보: ' + oTarget.getPoint()
							+'<span></div>');
					oInfoWnd.setPoint(oTarget.getPoint());
					oInfoWnd.setPosition({right : 0, top : 4});
					oInfoWnd.setVisible(true);
					oInfoWnd.autoPosition();
					return;
			}
			
	});
	
	return oMap;
}